package com.ruoyi.graduate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.graduate.domain.entity.MsMessageBoard;
import com.ruoyi.graduate.domain.param.MsMessageBoardAddParam;
import com.ruoyi.graduate.domain.param.MsMessageBoardPageParam;
import com.ruoyi.graduate.domain.param.MsMessageBoardUpdataParam;
import com.ruoyi.graduate.domain.param.MsMessageBoardUserPageParam;
import com.ruoyi.graduate.domain.vo.MsMessageBoardDetailVo;
import com.ruoyi.graduate.domain.vo.MsMessageBoardPageVo;
import com.ruoyi.graduate.domain.vo.MsMessageBoardUserPageVo;
import com.ruoyi.graduate.mapper.MsMessageBoardMapper;
import com.ruoyi.graduate.mapping.MsMessageBoardMapping;
import com.ruoyi.graduate.service.IMsMessageBoardService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IMsMessageBoardServiceImpl extends ServiceImpl<MsMessageBoardMapper, MsMessageBoard>
implements IMsMessageBoardService {

    @Autowired
    private MsMessageBoardMapper msMessageBoardMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    @Override
    public PageInfo pageList(MsMessageBoardPageParam param) {

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<MsMessageBoardPageVo> vo = msMessageBoardMapper.pageList(param.getMessageContent());

        return new PageInfo<>(vo);
    }

    @Override
    public MsMessageBoardDetailVo detail(Integer id) {
        return msMessageBoardMapper.detail(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(MsMessageBoardAddParam param) {

        MsMessageBoard add = MsMessageBoardMapping.INSTANCE.add(param);

        if (add.getImgUrl() != null) {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("user_id", add.getUserId());
            SysUserRole sysUserRole = sysUserRoleMapper.selectOne(qw);

            if (sysUserRole != null && sysUserRole.getRoleId() == 104) {

                return AjaxResult.error("为摄影师不能发送带有图片的留言，请修改后重新尝试");
            }
        }


        int insert = msMessageBoardMapper.insert(add);


        return insert > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updata(MsMessageBoardUpdataParam param) {
        UpdateWrapper uw = new UpdateWrapper();
        uw.eq("message_id", param.getMessageId());
        uw.set("message_content", param.getMessageContent());

        if (!StringUtils.isEmpty(param.getImgUrl())) {
            uw.set("img_url", param.getImgUrl());
        }

        int update = msMessageBoardMapper.update(null, uw);


        return update > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public List<MsMessageBoardUserPageVo> userPageList(Integer id) {

        List<MsMessageBoardUserPageVo> vos = msMessageBoardMapper.userPageList(id);

        return buildMessageTree(vos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(Integer id) {
        int i = msMessageBoardMapper.deleteById(id);

        QueryWrapper qw = new QueryWrapper();
        qw.eq("parent_id", id);

        msMessageBoardMapper.delete(qw);

        return i > 0 ? AjaxResult.success() : AjaxResult.error();
    }


    /**
     * 构建留言层级树（一级留言包含次级留言）
     */
    private List<MsMessageBoardUserPageVo> buildMessageTree(List<MsMessageBoardUserPageVo> allMessages) {
        // 用Map缓存所有留言（key=messageId，value=留言对象），方便快速查找父留言
        Map<Integer, MsMessageBoardUserPageVo> messageMap = new HashMap<>();
        for (MsMessageBoardUserPageVo message : allMessages) {
            messageMap.put(message.getMessageId(), message);
            // 初始化children列表，避免null
            message.setChildren(new ArrayList<>());
        }

        // 根留言列表（一级留言，parentId=0）
        List<MsMessageBoardUserPageVo> rootMessages = new ArrayList<>();

        for (MsMessageBoardUserPageVo message : allMessages) {
            Integer parentId = message.getParentId();
            if (parentId == null || parentId == 0) {
                // 一级留言，直接加入根列表
                rootMessages.add(message);
            } else {
                // 次级留言，找到父留言并添加到children中
                MsMessageBoardUserPageVo parentMessage = messageMap.get(parentId);
                if (parentMessage != null) {
                    parentMessage.getChildren().add(message);
                }
            }
        }

        return rootMessages;
    }
}
